package com.yhm.testSpringMvc.Thread;

import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class ThreadCallableAndFutureDemo {
    public static void main(String[] args) {


        ExecutorService executorService = Executors.newFixedThreadPool(2);
        List<Future<String>> futureList = new CopyOnWriteArrayList<Future<String>>();
        for (int i = 0; i < 10; i++) {
            futureList.add(
                    executorService.submit(new Callable<String>() {

                        @Override
                        public String call() throws Exception {

                            int time = new Random().nextInt(999);

                            Thread.sleep(time);

                            return Thread.currentThread().getName() + "_睡眠了" + time;
                        }
                    }));
        }

        executorService.shutdown();
        for (int i = 0; i < futureList.size(); i++) {
            try {
                System.out.println(futureList.get(i).get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
